package com.bamboo.ucenterservice.service.impl;

import com.bamboo.servicebase.exceptionhandler.BambooException;
import com.bamboo.ucenterservice.entity.RegisterVo;
import com.bamboo.ucenterservice.entity.UcenterMember;
import com.bamboo.ucenterservice.mapper.UcenterMemberMapper;
import com.bamboo.ucenterservice.service.UcenterMemberService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * <p>
 * 会员表 服务实现类
 * </p>
 *
 * @author jack.wu
 * @since 2020-07-14
 */
@Service
public class UcenterMemberServiceImpl extends ServiceImpl<UcenterMemberMapper, UcenterMember> implements UcenterMemberService {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 注册待完善
     * @param registerVo 注册vo
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void registerMember(RegisterVo registerVo) {

        String code = registerVo.getCode();
        String mobile = registerVo.getMobile();
        String nickname = registerVo.getNickname();
        String password = registerVo.getPassword();

        QueryWrapper<UcenterMember> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("mobile", mobile);
        Integer count = baseMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BambooException(20001, "该手机号已经注册");
        }
        QueryWrapper<UcenterMember> wrapper = new QueryWrapper<>();
        wrapper.eq("nickname", nickname);
        Integer nicknameCount = baseMapper.selectCount(wrapper);
        if (nicknameCount > 0) {
            throw new BambooException(20001, "该用户名已使用");
        }
        String codeCache = redisTemplate.opsForValue().get(mobile);
        if (!code.equals(codeCache)) {
            throw new BambooException(20001, "验证码错误");
        }
        // todo 密码加密
        UcenterMember member = new UcenterMember();
        member.setMobile(mobile);
        member.setNickname(nickname);
        member.setPassword(password);
        member.setIsDisabled(false);
        baseMapper.insert(member);
    }

    @Override
    public int getRegisterCount(String day) {
        return baseMapper.selectRegisterCount(day);
    }
}
